package model

import (
	"errors"
	"github.com/jinzhu/gorm"
)

type User struct {
	gorm.Model
	NickName string `json:"nick_name"`
	Account  string `json:"account"`
	Email    string `json:"email"`
	Password string `json:"password"`
	Icon     string `json:"icon"`
	Gender   uint8  `json:"gender"`
	Status   uint8  `json:"status"`
}

func (u *User) TableName() string {
	return "blog_user"
}

// Create 添加用户
func (u *User) Create(db *gorm.DB) error {
	return db.Create(&u).Error
}

func (u *User) Delete(db *gorm.DB) (int64, error) {
	res := db.Delete(&u)
	return res.RowsAffected, res.Error
}

func (u *User) Update(db *gorm.DB, values map[string]any) (int64, error) {
	res := db.Model(&u).Updates(values)
	return res.RowsAffected, res.Error
}

func (u *User) GetById(db *gorm.DB) (User, error) {
	var user User
	err := db.Where("id = ?", u.ID).First(&user).Error
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		return user, err
	}
	return user, nil
}

func (u *User) GetByEmail(db *gorm.DB) (*User, error) {
	var user User
	if err := db.Where("email = ?", u.Email).First(&user).Error; err != nil {
		return nil, err
	}
	return &user, nil
}

func (u *User) GetByAccount(db *gorm.DB) (*User, error) {
	var user User
	if err := db.Where("account = ?", u.Account).First(&user).Error; err != nil {
		return nil, err
	}
	return &user, nil
}
